package com.bnyy.medicalHousekeeper.moudle.message.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.ViewTreeObserver;
import android.widget.TextView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bnyy.medicalHousekeeper.R;
import com.bnyy.medicalHousekeeper.base.BaseActivityImpl;
import com.bnyy.medicalHousekeeper.moudle.message.adapter.ContactAdapter;
import com.bnyy.medicalHousekeeper.moudle.message.adapter.GroupChatMemberAdapter;
import com.bnyy.medicalHousekeeper.request.BaseObserverImpl;
import com.bnyy.medicalHousekeeper.request.RequestManager;
import com.bnyy.message.bean.Contact;
import com.bnyy.message.bean.ContactGroup;
import com.bnyy.message.bean.GroupChatSetting;
import com.bnyy.message.enums.GroupChatIdentity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.function.Consumer;

import butterknife.BindView;

/**
 * Author : 关炳鹏
 * Description :
 * Date : 2022/11/21
 **/
public class GroupChatManagersActivity extends BaseActivityImpl {
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.tv_count)
    TextView tvCount;

    private GroupChatSetting groupChatSetting;
    private GroupChatMemberAdapter adapter;
    private ActivityResultLauncher<Intent> addManagerLauncher, removeManagerLauncher;

    public static void show(Context context, GroupChatSetting groupChatSetting, ActivityResultLauncher<Intent> launcher) {
        Intent intent = new Intent(context, GroupChatManagersActivity.class);
        intent.putExtra("groupChatSetting", groupChatSetting);
        launcher.launch(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_message_group_chat_managers;
    }

    @Override
    public String getTitleStr() {
        return "群管理员";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        groupChatSetting = (GroupChatSetting) getIntent().getSerializableExtra("groupChatSetting");

        addManagerLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result != null) {
                    Intent data = result.getData();
                    if (data != null) {
                        ArrayList<Contact> contacts = (ArrayList<Contact>) data.getSerializableExtra(SelectContactActivity.RESULT_SELECTED_CONTACTS);
                        if (contacts != null && contacts.size() > 0) {
                            HashMap<String, Object> params = new HashMap<>();
                            params.put("id", groupChatSetting.getId());
                            ArrayList<HashMap<String, Integer>> users = new ArrayList<>();
                            contacts.forEach(new Consumer<Contact>() {
                                @Override
                                public void accept(Contact contact) {
                                    HashMap<String, Integer> map = new HashMap<>();
                                    map.put("id", contact.getId());
                                    map.put("role_id", contact.getRole_id());
                                    users.add(map);
                                }
                            });
                            params.put("users", users);

                            requestManager.request(requestManager.mMessageRetrofitService.addGroupChatManager(RequestManager.getJsonRequestBody(params)),
                                    new BaseObserverImpl<Object>(mContext) {
                                        @Override
                                        public void onSuccess() {
                                            super.onSuccess();
                                            HashSet<Integer> selectedContactIds = (HashSet<Integer>) data.getSerializableExtra(SelectContactActivity.RESULT_SELECTED_CONTACT_IDS);
                                            ArrayList<ContactGroup.Member> managers = new ArrayList<>();

                                            for (ContactGroup.Member member : groupChatSetting.getUser_list()) {
                                                if (GroupChatIdentity.getGroupAuthority(member.getAuth_type()) == GroupChatIdentity.MANAGER) {
                                                    managers.add(member);
                                                } else if (selectedContactIds.contains(member.getId())) {
                                                    member.setAuth_type(GroupChatIdentity.MANAGER.getAuthority()[0]); // 权限设置为群管理员
                                                    managers.add(member);
                                                }
                                            }
                                            refreshManagers(managers);
                                        }
                                    });
                        }
                    }
                }
            }
        });

        removeManagerLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result != null) {
                    Intent data = result.getData();
                    if (data != null) {
                        ArrayList<Contact> contacts = (ArrayList<Contact>) data.getSerializableExtra(SelectContactActivity.RESULT_SELECTED_CONTACTS);
                        if (contacts != null && contacts.size() > 0) {
                            HashMap<String, Object> params = new HashMap<>();
                            params.put("id", groupChatSetting.getId());
                            ArrayList<HashMap<String, Integer>> users = new ArrayList<>();
                            contacts.forEach(new Consumer<Contact>() {
                                @Override
                                public void accept(Contact contact) {
                                    HashMap<String, Integer> map = new HashMap<>();
                                    map.put("id", contact.getId());
                                    map.put("role_id", contact.getRole_id());
                                    users.add(map);
                                }
                            });
                            params.put("users", users);

                            requestManager.request(requestManager.mMessageRetrofitService.removeGroupChatManager(RequestManager.getJsonRequestBody(params)),
                                    new BaseObserverImpl<Object>(mContext) {
                                        @Override
                                        public void onSuccess() {
                                            super.onSuccess();
                                            HashSet<Integer> selectedContactIds = (HashSet<Integer>) data.getSerializableExtra(SelectContactActivity.RESULT_SELECTED_CONTACT_IDS);
                                            ArrayList<ContactGroup.Member> managers = new ArrayList<>();

                                            for (ContactGroup.Member member : groupChatSetting.getUser_list()) {
                                                if (GroupChatIdentity.getGroupAuthority(member.getAuth_type()) == GroupChatIdentity.MANAGER) {
                                                    if (selectedContactIds.contains(member.getId())) {
                                                        member.setAuth_type(GroupChatIdentity.MEMBER.getAuthority()[0]); // 权限设置为群员
                                                    } else {
                                                        managers.add(member);
                                                    }
                                                }
                                            }
                                            refreshManagers(managers);
                                        }
                                    });
                        }
                    }
                }
            }
        });

        recyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                recyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                int spanCount = 5;
                recyclerView.setLayoutManager(new GridLayoutManager(mContext, spanCount));
                int itemWidth = (recyclerView.getWidth() - ((spanCount + 1) * recyclerView.getPaddingStart())) / spanCount;

                GroupChatSetting.GroupChatManage groupChatManage = groupChatSetting.getGroup_admin();
                int max = groupChatManage.getAdmin_number(); // 群管理最大人数

                adapter = new GroupChatMemberAdapter(mContext, itemWidth,
                        new GroupChatMemberAdapter.Operate() {
                            @Override
                            public void onAdd() {
                                ArrayList<ContactGroup.Member> target = new ArrayList<>();
                                for (ContactGroup.Member member : groupChatSetting.getUser_list()) {
                                    if (GroupChatIdentity.getGroupAuthority(member.getAuth_type()) == GroupChatIdentity.MEMBER) {
                                        target.add(member);
                                    }
                                }
                                SelectContactActivity.show(
                                        mContext,
                                        "添加管理员",
                                        "确认要添加选中群成员为群管理员吗？",
                                        false,
                                        true,
                                        new ContactAdapter.ConstantItem("全部群成员"),
                                        target,
                                        addManagerLauncher
                                );
                            }

                            @Override
                            public void onRemove(ArrayList<ContactGroup.Member> members) {
                                SelectContactActivity.show(
                                        mContext,
                                        "移除管理员",
                                        "确认要移除选中的群管理员吗？",
                                        false,
                                        false,
                                        null,
                                        members,
                                        removeManagerLauncher
                                );
                            }

                            @Override
                            public void onClick(ContactGroup.Member member) {

                            }
                        });

                recyclerView.setAdapter(adapter);

                ArrayList<ContactGroup.Member> managers = new ArrayList<>();
                for (ContactGroup.Member member : groupChatSetting.getUser_list()) {
                    if (GroupChatIdentity.getGroupAuthority(member.getAuth_type()) == GroupChatIdentity.MANAGER) {
                        managers.add(member);
                    }
                }
                refreshManagers(managers);
            }
        });
    }

    private void refreshManagers(ArrayList<ContactGroup.Member> managers) {
        GroupChatSetting.GroupChatManage groupChatManage = groupChatSetting.getGroup_admin();
        int max = groupChatManage.getAdmin_number(); // 群管理最大人数
        int size = managers.size(); // 群管理人数

        tvCount.setText("群管理员（" + managers.size() + "/" + max + "）");

        boolean enableAdd = size < max;
        if (enableAdd) {
            boolean noMember = true;
            for (ContactGroup.Member member : groupChatSetting.getUser_list()) {
                if (GroupChatIdentity.getGroupAuthority(member.getAuth_type()) == GroupChatIdentity.MEMBER) {
                    noMember = false;
                    break;
                }
            }
            if (noMember) {
                enableAdd = false;
            }
        }

        //  群管理人数小于群员总数并且群管理人数小于群管理最大人数可以新增， size > 0 时可以移除
        adapter.refresh(enableAdd, size > 0, managers);
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        intent.putExtra("groupChatSetting", groupChatSetting);
        setResult(RESULT_OK, intent);

        super.onBackPressed();
    }
}























